#!/usr/bin/env python
# -*- coding: utf-8 -*- 
#############################################################################
# GMangas
# Copyright (C) 2008  Ferraro Luciano (aka Lux) <luciano.ferraro@gmail.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

import utils

class Main:
    def __init__(self, main, glade):
        self.main = main
        self._ = glade.get_widget("image")

        self.pixbuf, self.width, self.height = None, None, None
        self.cache = [] # alist
        self.cache_size = 8

    def set_image(self, file_path, nocache=False):
        #file_path = str with file's path
        #scale = int with percentage to resize the image
        
        key = (file_path, self.main.core.optimal_scale_rate)
        if nocache:
            utils.rmassoc(key, self.cache)
        
        cache = utils.assoc(key, self.cache)
        if cache:
            self.pixbuf = cache
        else:
            pixbuf = gtk.gdk.pixbuf_new_from_file(file_path)
            self.width, self.height = pixbuf.get_width(), pixbuf.get_height()
            scale = self.main.core.optimal_scale()
            self.width, self.height = int(self.width*scale), int(self.height*scale)
            self.pixbuf = pixbuf.scale_simple(self.width, self.height, gtk.gdk.INTERP_HYPER)

        utils.pushnew((key, self.pixbuf), self.cache)
        self.cache = self.cache[- self.cache_size : ]
        self._.set_from_pixbuf(self.pixbuf)
